﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FluentData;
using HtmlAgilityPack;
using TaoBaoKe.Common;
using System.Net;
using System.Text.RegularExpressions;
namespace FormTBK.Function
{
    public partial class GetKeyFromMY : Form
    {
        public GetKeyFromMY()
        {
            InitializeComponent();
        }
        IDbContext dbContext = new DbContext().ConnectionString("server=.;User ID=sa;Password=111111;database=test;Connection Reset=FALSE", new SqlServerProvider());

        private void GetKeyFromMY_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            int begin = Convert.ToInt32(this.tbFrom.Text.Trim());
            int end = Convert.ToInt32(this.tbTo.Text.Trim());
            int current = begin;

            HtmlWeb w = new HtmlWeb();
            w.OverrideEncoding = Encoding.UTF8;
            w.UseCookies = false;
            w.NeedParse = false;
            w.PreRequest += req;
            HtmlAgilityPack.HtmlDocument d;
            while (current <= end)
            {
                d = w.Load("http://www.ey7m.com/ad.php?kid="+current);
                string result = d.Text.Replace("\n", "").Replace("\r", "");
                Match m = result.Match("<title>(?<title>.*?)</title>");
                if (m.Success)
                {
                    string key = m.Groups["title"].Value;

                    dbContext.Sql("insert into MYData values(" + current + ",'" + key + "')").Execute();
                }


                current++;
                this.tbCurrent.Text = current.ToString();
            }
            MessageBox.Show("完成");
        }
        private bool req(System.Net.HttpWebRequest request)
        {
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.AutomaticDecompression = DecompressionMethods.GZip;
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
            return true;
        }
        private void tbTo_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
